import formbuild
import formencode
import logging
import os
import shutil

from pylons import request, response, session
from pylons import tmpl_context as c

from pylons.controllers.util import abort, redirect_to, url_for
from pylons.decorators import validate
from pylons.templating import render_mako as render

from formhandling.lib.base import BaseController

log = logging.getLogger(__name__)

class EmailForm1(formencode.Schema):
    allow_extra_fields = True
    filter_extra_fields = True
    email = formencode.validators.Email(not_empty=True)

class SimpleEmail(formencode.validators.Email):
    def _to_python(self, value, c):
        if not value.endswith(c.domain):
            raise formencode.validators.Invalid('Email addresses must end in: %s' % \
                                                c.domain, value, c)
        return formencode.validators.Email._to_python(self, value, c)

class EmailForm2(formencode.Schema):
    allow_extra_fields = True
    filter_extra_fields = True
    email = SimpleEmail(not_empty=True)

class EmailForm3(formbuild.Form):
    pass

permanent_store = r'Enter Your Path here'

class FormController(BaseController):

    def index(self):
        return 'Form Handling Sample'

    def form1(self):
        return render('/form1.mako')

    @validate(schema=EmailForm1(), form='form1')
    def email1(self):
        # Code to perform some action based on the form data
        # ...
        redirect_to(action='result')

    def result(self):
        return 'Your data was successfully submitted'

    def form2(self):
        return render('/form2.mako')

    def email2(self):
        schema = EmailForm1()
        try:
            form_result = schema.to_python(request.params)

        except formencode.validators.Invalid, error:
            return 'Invalid: %s' % error

        else:
            return 'Your email is: %s' % form_result.get('email')

    def form3(self):
        return render('/form3.mako')

    def email3(self):
        schema = EmailForm2()

        try:
            c.domain = 'example.com'
            form_result = schema.to_python(request.params, c)

        except formencode.validators.Invalid, error:
            c.form_result = error.value
            c.form_errors = error.error_dict or {}
            return render('/form3.mako')

        else:
            return 'Your email is: %s' % form_result.get('email')

    def form4(self):
        results, errors, response = formbuild.handle(
            schema=EmailForm1(),     # Your FormEncode schema for the form to be validated
            template='/form4.mako', # The template containg the code that builds your form
            form=EmailForm3         # The FormBuild Form definition you wish to use
            )
        if response:
            # The form validation failed so re-display the form with the auto-generted response
            # containing submitted values and errors or do something with the errors
            return response
        else:
            # The form validated, do something useful with results.
            return 'Your email is: %s' % results.get('email')

    def formup(self):
        return render('/upload.mako')

    def upload(self):
        myfile = request.POST['myfile']
        permanent_file = open(os.path.join(permanent_store,
                                           myfile.filename.lstrip(os.sep)),'w')
        shutil.copyfileobj(myfile.file, permanent_file)
        myfile.file.close()
        permanent_file.close()
        return 'Successfully uploaded: %s, description: %s' % \
            (myfile.filename, request.POST['description'])
